package com.mathlearning.auth.entity;

import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDateTime;

@Data
@Entity
@Table(name = "conversations",
       uniqueConstraints = @UniqueConstraint(columnNames = {"user_a_id", "user_b_id"}),
       indexes = {
           @Index(name = "idx_user_a_time", columnList = "user_a_id, last_message_time"),
           @Index(name = "idx_user_b_time", columnList = "user_b_id, last_message_time")
       })
public class Conversation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, name = "user_a_id")
    private Long userAId;  // 用户A的ID（较小的ID）

    @Column(nullable = false, name = "user_b_id")
    private Long userBId;  // 用户B的ID（较大的ID）

    @Column(length = 500, name = "last_message")
    private String lastMessage;  // 最后一条消息

    @Column(name = "last_message_time")
    private LocalDateTime lastMessageTime;  // 最后消息时间

    @Column(nullable = false, name = "update_time")
    private LocalDateTime updateTime;

    @Column(nullable = false, updatable = false, name = "create_time")
    private LocalDateTime createTime;

    @PrePersist
    protected void onCreate() {
        createTime = LocalDateTime.now();
        updateTime = LocalDateTime.now();
    }

    @PreUpdate
    protected void onUpdate() {
        updateTime = LocalDateTime.now();
    }

    /**
     * 创建会话（确保userAId < userBId）
     */
    public static Conversation create(Long userId1, Long userId2) {
        Conversation conversation = new Conversation();
        if (userId1 < userId2) {
            conversation.setUserAId(userId1);
            conversation.setUserBId(userId2);
        } else {
            conversation.setUserAId(userId2);
            conversation.setUserBId(userId1);
        }
        return conversation;
    }

    /**
     * 获取对方用户ID
     */
    public Long getOtherUserId(Long currentUserId) {
        return currentUserId.equals(userAId) ? userBId : userAId;
    }
}








